import React, { Component } from "react";
import { connect } from "react-redux";
import { messages } from "share/common";
import {Button, Checkbox, Form, Input, message, Select, Switch, Spin, Row, Col} from "antd";
import Priority from "components/template/priority";
import errorMessage from "share/errorMessage";
import dataSource from '../beep-timer.data';
import beepTimerService from "../beep-timer.service";
import 'styles/setting/beep-timer/slide-content/remind-content.scss'
import Selector from "components/selector";
import WrapFormItem from "components/wrap-form-item";

const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
const CheckboxGroup = Checkbox.Group;
const { remindTypesOption, consumeTypesOption, billingPeriodTypesOption } = dataSource;

@Form.create()
@connect(mapStateToProps)
class BusinessCardContent extends Component {

  state = {
    loading: false,
    cardLoading: false,
    priority: this.props.info.id ? {
      levelCode: this.props.info.levelCode,
      levelOrgId: this.props.info.levelCode === 'TENANT' ? this.props.info.tenantID : this.props.info.companyOID,
      levelOrgName: this.props.info.levelOrgName
    } : {
      levelCode: 'TENANT',
      levelOrgId: this.props.tenant.id,
      levelOrgName: this.props.tenant.tenantName
    },
    bankCardTypesOption: [],
    dateError: ''
  };

  dataErrorMsg = messages('common.can.not.be.empty',{arg1: messages('basic-13.key223')/*触发日期*/})/*{arg1} 不能为空*/;

  componentDidMount() {
    this.getBankCardOption();
  };

  //获取商务卡列表
  getBankCardOption() {
    this.setState({ cardLoading: true });
    beepTimerService.getBusinessCardType(this.props.company.companyOID)
      .then(res => {
        let bankCardTypesOption = [];
        res.data.rows && res.data.rows.map(item => {
          bankCardTypesOption.push({ label: item.description, value: item.cardTypeCode })
        });
        this.setState({ bankCardTypesOption })
      })
      .finally(() => this.setState({ cardLoading: false }))
  }

  handleSave = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      this.setState({ dateError: (!values.hour && values.hour !== 0 || !values.date) ? this.dataErrorMsg : '' });
      if (!err) {
        if (!values.priority || !values.priority.levelOrgId) {
          message.error(messages('basic-13.key220')/*请选择所属组织*/);
          return;
        }
        const { info } = this.props;
        const { levelCode, levelOrgId, companyOID } = values.priority;
        let params = {
          levelCode,
          enabledFlag: values.enabledFlag,
          date: values.date,
          hour: parseInt(values.hour),
          code: 'BankCardTask',
          params: JSON.stringify({
            title: values.title,
            content: values.content,
            consumeTypes: values.consumeTypes,
            bankCardTypes: values.bankCardTypes,
            remindTypes: values.remindTypes,
            billingPeriodTypes: values.billingPeriodTypes
          })
        };
        if (levelCode === 'TENANT') {
          params.tenantID = levelOrgId;
        } else {
          params.companyOID = companyOID;
        }
        info.id && (params.id = info.id);
        this.setState({ loading: true });
        beepTimerService.newBeepTimer(params)
          .then(() => {
            message.success(messages('common.save.success',{arg1: ""})/*{arg1} 保存成功*/);
            this.props.close(true);
          })
          .catch(e => errorMessage(e.response))
          .finally(() => this.setState({ loading: false }))
      }
    })
  };

  setDateError = (value, type) => {
    const { getFieldValue } = this.props.form;
    const date = type === 'date' ? value : getFieldValue('date');
    const hour = type === 'date' ? getFieldValue('hour') : value;
    this.setState({ dateError: (!hour || !date) ? this.dataErrorMsg : '' });
  }

  render() {
    const { info, form: { getFieldDecorator } } = this.props;
    const { loading, cardLoading, priority, bankCardTypesOption, dateError } = this.state;
    const paramsData = JSON.parse(info.params || '{}');
    let hourOption = [];
    let dateOption = [];
    for (let i = 0; i <= 23; i++) {
      hourOption.push(<Option value={i + ''}>{i + ":00"}</Option>)
    }
    for (let i = 1; i <= 31; i++) {
      dateOption.push(<Option value={i + ''}>{i}</Option>)
    }
    return (
      <div className="remind-content">
        <Form className="new-form remind-content-form">
          <FormItem label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator("enabledFlag", {
              valuePropName: "checked",
              initialValue: info.id ? info.enabledFlag : true
            })(
              <Switch />
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key9')/*所属组织*/}>
            {getFieldDecorator('priority', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key9')/*所属组织*/})/*{arg1} 不能为空*/
              }],
              initialValue: priority
            })(
              <Priority
                top='TENANT'
                defaultValue={priority}
                showLabel={false}
                showCompanyComponent={false}
                disabled={!!info.id}
              />
            )}
          </FormItem>
          <div className='sub-title'>{messages('basic-13.key15')/*消息内容*/}</div>
          <FormItem label={messages('basic-13.key16')/*消息标题*/}>
            {getFieldDecorator('title', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key16')/*消息标题*/})/*{arg1} 不能为空*/
              }, {
                max: 50,
                message: messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/
              }],
              initialValue: paramsData.title
            })(
              <Input placeholder={messages('basic-13.key221')/*商务卡消息报销提醒*/} />
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key15')/*消息内容*/}>
            {getFieldDecorator('content', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key15')/*消息内容*/})/*{arg1} 不能为空*/
              }, {
                max: 100,
                message: messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/
              }],
              initialValue: paramsData.content
            })(
              <TextArea placeholder={messages('basic-13.key222')/*请及时报销*/} />
            )}
          </FormItem>
          <div className='sub-title'>{messages('basic-13.key18')/*消息触发*/}</div>
          <FormItem label={messages('basic-13.key34')/*提醒方式*/} className="checkbox-item">
            {getFieldDecorator('remindTypes', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key34')/*提醒方式*/})/*{arg1} 不能为空*/
              }],
              initialValue: info.id ? paramsData.remindTypes : []
            })(
              <CheckboxGroup options={remindTypesOption}/>
            )}
          </FormItem>
          <FormItem
            label={messages('basic-13.key223')/*触发日期*/}
            help={dateError}
            validateStatus={dateError ? 'error' : ''}
          >
            {messages('basic-13.key143')/*每月*/}
            {getFieldDecorator('date', {
              initialValue: info.id ? info.date : undefined
            })(
              <Select
                placeholder={messages('basic-13.key86')/*请选择temp*/}
                className="time-select"
                onChange={value => this.setDateError(value + '', 'date')}
              >
                {dateOption}
              </Select>
            )}
            {messages('basic-13.key144')/*日*/}
            {getFieldDecorator('hour', {
              initialValue: info.id ? info.hour : undefined
            })(
              <Select
                placeholder={messages('basic-13.key86')/*请选择temp*/}
                className="time-select"
                onChange={value => this.setDateError(value + '', 'hour')}
              >
                {hourOption}
              </Select>
            )}
            {messages('basic-13.key145')/*时提醒员工*/}
          </FormItem>
          <div className='sub-title'>{messages('basic-13.key224')/*附加规则*/}</div>
          Row
          <FormItem label={messages('basic-13.key146')/*商务卡*/} className="checkbox-item">
            {cardLoading ? <Spin size="small" /> : (
              getFieldDecorator('bankCardTypes', {
                rules: [{
                  required: true,
                  message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key146')/*商务卡*/})/*{arg1} 不能为空*/
                }],
                initialValue: info.id ? paramsData.bankCardTypes : []
              })(
                <CheckboxGroup options={bankCardTypesOption}/>
              )
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key147')/*消费数据类型*/} className="checkbox-item">
            {getFieldDecorator('consumeTypes', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key147')/*消费数据类型*/})/*{arg1} 不能为空*/
              }],
              initialValue: info.id ? paramsData.consumeTypes : []
            })(
              <CheckboxGroup options={consumeTypesOption}/>
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key148')/*账单期数*/} className="checkbox-item">
            {getFieldDecorator('billingPeriodTypes', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty',{arg1: messages('basic-13.key148')/*账单期数*/})/*{arg1} 不能为空*/
              }],
              initialValue: info.id ? paramsData.billingPeriodTypes : []
            })(
              <CheckboxGroup options={billingPeriodTypesOption}/>
            )}
          </FormItem>
          <div className='slide-footer'>
            <Button
              type='primary'
              loading={loading}
              disabled={this.props.disabled}
              onClick={this.handleSave}
            >
              {messages('common.save')/*保存*/}
            </Button>
            <Button onClick={() => this.props.close()}>{messages('common.back')/*返回*/}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    company: state.login.company
  }
}

export default BusinessCardContent;
